package com.inspire.springboot.test.ttl;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.concurrent.*;

/*
第二种使用TTl方式：javaagent方式
启动main之前配置：-javaagent:D:\dev_file\Git_file\transmittable-thread-local\target\transmittable-thread-local-3.x-SNAPSHOT.jar
 */
public class TransmittableThreadLocalDemoMode2 {
    private static TimeUnit keepAliveTimeUnit = TimeUnit.MINUTES;

    private static ExecutorService tomcatExecutors = new ThreadPoolExecutor(8, 16,
            60L, keepAliveTimeUnit, new LinkedBlockingDeque<>(100));
    private static Executor controlExectutors=Executors.newFixedThreadPool(5);
    private static ThreadLocal<Integer> itl=new TransmittableThreadLocal<>();

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            tomcatExecutors.submit(new TransmittableThreadLocalDemoMode2.ControlTask(i));
        }

        tomcatExecutors.shutdown();
    }

    static class ControlTask implements Runnable {

        private int i;

        public ControlTask(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            itl.set(i);
            System.out.println(Thread.currentThread().getName() + ":" + i);
            // ttl线程池只有execute()方法
            controlExectutors.execute(new TransmittableThreadLocalDemoMode2.BusinessTask(Thread.currentThread().getName()));
        }
    }

    static class BusinessTask implements Runnable {
        private String parentThreadName;

        public BusinessTask(String parentThreadName) {
            this.parentThreadName = parentThreadName;
        }



        @Override
        public void run() {
            System.out.println("parent:" + parentThreadName + ",son:"+Thread.currentThread().getName()+",id: " + itl.get());
        }
    }
}
